## This file is for analysing spatial paneldata set "numbered_tx_county_emp_wells" using R package "splm"

## Export the following output to a txt file.
## sink(file = "/shared.scratch/xz1/creatJob.txt", append = FALSE, type = c("output", "message"), split = FALSE)

## clear the memory
rm(list = ls())

## ## Install new packages
## install.packages("plm")
## install.packages("splm")
## install.packages("spdep")

## Load new packages
library("plm")            # Panel data model
library("splm");          # Spatial panel data model
library("spdep");         # Define listw class, and transform it into a sparse matrix

## Import data as a data.frame.
monData <- read.csv("~/monData.csv", header = T)

## Import spacial weights matrix.
wmat = as.matrix(read.csv("/shared.scratch/xz1/adjmatrix.csv", header = TRUE, row.names = 1))

fm.emp <- emp ~ wells + cumuwells + newcap + cumucap
fm.wage <- realwage ~ wells + cumuwells + newcap + cumucap

#######################
## LM implementation ##
#######################


## spacial weights matrix
wmatl <- mat2listw(wmat, style = "W");

## Spatial lag model, random effects
lagre <- spml(formula = fm.emp, data = txData, index = "county", listw = wmatl,  model = "random", lag = T, spatial.error = "none")
summary(lagre)

## Two-way fixed effects
lagtwfe <- spml(formula = fm.emp, data = txData, index = "county", listw = wmatl, model = "within", lag = T, spatial.error = "none", effect = "twoways", method = "eigen", na.action = na.fail, quiet = TRUE, zero.policy = NULL, interval = NULL, tol.solve = 1e-10, control = list(), legacy = FALSE)
summary(lagtwfe)

errtwfe <- spml(formula = fm.emp, data = txData, index = "county", listw = wmatl, model = "within", lag = F, spatial.error = "b", effect = "twoways", method = "eigen", na.action = na.fail, quiet = TRUE, zero.policy = NULL, interval = NULL, tol.solve = 1e-10, control = list(), legacy = FALSE)
summary(errtwfe)

## Wage
## Spatial lag model, random effects
lagre.wage <- spml(formula = fm.emp, data = txData, index = "county", listw = wmatl,  model = "random", lag = T, spatial.error = "none")
summary(lagre.wage)

## Two-way fixed effects
lagtwfe.wage <- spml(formula = fm.emp, data = txData, index = "county", listw = wmatl, model = "within", lag = T, spatial.error = "none", effect = "twoways", method = "eigen", na.action = na.fail, quiet = TRUE, zero.policy = NULL, interval = NULL, tol.solve = 1e-10, control = list(), legacy = FALSE)
summary(lagtwfe.wage)

errtwfe.wage <- spml(formula = fm.emp, data = txData, index = "county", listw = wmatl, model = "within", lag = F, spatial.error = "b", effect = "twoways", method = "eigen", na.action = na.fail, quiet = TRUE, zero.policy = NULL, interval = NULL, tol.solve = 1e-10, control = list(), legacy = FALSE)
summary(errtwfe.wage)


## sink()
